//
//  PubH5.m
//  WuyouTang
//
//  Created by YunBao on 2018/7/30.
//  Copyright © 2018年 cat. All rights reserved.
//

#import "PubH5.h"
#import "YBGetProVC.h"
#import "YBShareView.h"
#import "YBTabBarController.h"
#import <WebKit/WebKit.h>
@interface PubH5 ()<WKNavigationDelegate>
{
    UIView *_shadowView;
}
@property (nonatomic,strong) WKWebView *WKWebView;
@property (nonatomic,strong) CALayer *progresslayer;
@end

@implementation PubH5
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id) self;
    self.WKWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 64+statusbarHeight, _window_width, _window_height-64-statusbarHeight)];
    self.WKWebView.navigationDelegate = self;
    [self.view addSubview:self.WKWebView];

    if([_url containsString:@"appapi/userreport/"] ||[_url containsString:@"appapi/message"] ||[_url containsString:@"appapi/goodsorderrefund"] ){//||[_url containsString:@"appapi/shopcash/"]
        self.view.backgroundColor = UIColor.whiteColor;//RGB(250, 250, 250);
        self.subNavi.backgroundColor = UIColor.whiteColor;
        self.titleL.textColor = UIColor.blackColor;
        [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
        self.naviLine.hidden = NO;
        self.naviLine.backgroundColor = RGB(245, 245, 245);
        _WKWebView.backgroundColor = UIColor.whiteColor;

    }else{
        self.view.backgroundColor = Normal_Color;
        _WKWebView.backgroundColor = Normal_Color;

    }
    
    self.rightBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 8, 0, 8);
    [self.rightBtn setImage:[UIImage imageNamed:@"分享-赚钱"] forState:0];
    
    self.progresslayer = [[CALayer alloc]init];
    self.progresslayer.frame = CGRectMake(0, 0, _window_width*0.1, 2);
    self.progresslayer.backgroundColor = Pink_Cor.CGColor;
    [self.WKWebView.layer addSublayer:self.progresslayer];
    
    [self.WKWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.WKWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    
    _url =  [_url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    if ([_url containsString:@"?"]) {
        if (![PublicObj checkNull:[Config getOwnID]] && ![_url containsString:@"uid"]) {
            _url = [_url stringByAppendingFormat:@"&uid=%@&token=%@",[Config getOwnID],[Config getOwnToken]];
        }
        _url = [_url stringByAppendingFormat:@"&lang=%@",[YBLanguageTools serviceLang]];
    }else {
        _url = [_url stringByAppendingFormat:@"?lang=%@",[YBLanguageTools serviceLang]];
        if (![PublicObj checkNull:[Config getOwnID]] && ![_url containsString:@"uid"]) {
            _url = [_url stringByAppendingFormat:@"&uid=%@&token=%@",[Config getOwnID],[Config getOwnToken]];
        }
    }
    
    [self.WKWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_url]]];
    
    _shadowView = [[UIView alloc]initWithFrame:CGRectMake(0, 64+statusbarHeight+2, _window_width, _window_height-64-statusbarHeight-2)];
    if([_url containsString:@"appapi/userreport/"] ||[_url containsString:@"appapi/message"] ||[_url containsString:@"appapi/goodsorderrefund"] ){
        _shadowView.backgroundColor = UIColor.whiteColor;

    }else{
        _shadowView.backgroundColor = Normal_Color;
    }
    [self.view addSubview:_shadowView];
    
}
// 观察者
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progresslayer.opacity = 1;
        float floatNum = [[change objectForKey:@"new"] floatValue];
        self.progresslayer.frame = CGRectMake(0, 0, _window_width*floatNum, 2);
        if (floatNum == 1) {
            __weak __typeof(self)weakSelf = self;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                weakSelf.progresslayer.opacity = 0;
            });
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                weakSelf.progresslayer.frame = CGRectMake(0, 0, 0, 3);
                _shadowView.hidden = YES;
            });
        }
    }else if ([keyPath isEqualToString:@"title"]){//网页title
        if (object == self.WKWebView){
            self.titleL.text = self.WKWebView.title;
            NSString *url = _WKWebView.URL.absoluteString;
            url = [url lowercaseString];
            if ([url containsString:@"appapi/agent/agent"]) {
                self.rightBtn.hidden = NO;
            }else{
                self.rightBtn.hidden = YES;
            }
        }else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
    
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    NSString *url = navigationAction.request.URL.absoluteString;
    if (navigationAction.targetFrame.isMainFrame) {
        NSLog(@"target is main ... %@",url);
        if (navigationAction.sourceFrame.mainFrame) {
            NSLog(@"source is main...%@",url);
            //是原始url 放行
            if ([_url isEqualToString:url]) {
                decisionHandler(WKNavigationActionPolicyAllow);
                NSLog(@"放行bbbbbbbbbbbbbbbbb...%@",url);
                return;
            }
            if ([url containsString:@"copy://"]) {
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                //将拿到的字符串去掉 copy:// 得到QQ号，复制到剪切板
                pasteboard.string = [url stringByReplacingOccurrencesOfString:@"copy://" withString:@""];
                [MBProgressHUD showPop:YZMsg(@"复制成功")];
                decisionHandler(WKNavigationActionPolicyCancel);
                return;
            }
            if ([url containsString:@"copycode://"]) {
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                //将拿到的字符串去掉 copy:// 得到QQ号，复制到剪切板
                pasteboard.string = [url stringByReplacingOccurrencesOfString:@"copycode://" withString:@""];
                 [MBProgressHUD showPop:YZMsg(@"复制成功")];
                decisionHandler(WKNavigationActionPolicyCancel);
                return;
            }
            if ([url containsString:@"share://friends"]) {
                
                decisionHandler(WKNavigationActionPolicyCancel);
                return;
            }
            if ([url containsString:@"userreport://"]) {
                //用户举报
                [self dismissViewControllerAnimated:YES completion:nil];
                [self.navigationController popViewControllerAnimated:YES];
                decisionHandler(WKNavigationActionPolicyCancel);
                return;
            }
            if ([url containsString:@"cash://"]) {
                YBGetProVC *vc = [[YBGetProVC alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
                decisionHandler(WKNavigationActionPolicyCancel);
                return;
            }
            if ([url containsString:@"agentshare://"]) {
                [self doShare];
                decisionHandler(WKNavigationActionPolicyCancel);
                return;
            }
            if ([url containsString:@"tel:"]) {
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
                decisionHandler(WKNavigationActionPolicyCancel);
                return;
            }
             
            
        } else {
            NSLog(@"source is not main...%@",url);
        }
    } else {
        NSLog(@"target is not main ... %@",url);
    }
    decisionHandler(WKNavigationActionPolicyAllow);
    NSLog(@"在发送请求之前：%@",navigationAction.request.URL.absoluteString);
}


-(void)dealloc{
    NSLog(@"WKWebView dealloc------------");
    [self.WKWebView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.WKWebView removeObserver:self forKeyPath:@"title"];

}

//-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//    NSString *url = request.URL.absoluteString;
//    
//    if ([url containsString:@"copy://"]) {
//        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
//        //将拿到的字符串去掉 copy:// 得到QQ号，复制到剪切板
//        pasteboard.string = [url stringByReplacingOccurrencesOfString:@"copy://" withString:@""];
//        return NO;
//    }
//    if ([url containsString:@"share://friends"]) {
//        
//        return NO;
//    }
//    if ([url containsString:@"userreport://"]) {
//        //用户举报
//        [self dismissViewControllerAnimated:YES completion:nil];
//        [self.navigationController popViewControllerAnimated:YES];
//        return NO;
//    }
//    if ([url containsString:@"cash://"]) {
//        YBGetProVC *vc = [[YBGetProVC alloc] init];
//        [self.navigationController pushViewController:vc animated:YES];
//        return NO;
//    }
//    if ([url containsString:@"agentshare://"]) {
//        [self doShare];
//        return NO;
//    }
//
//    return YES;
//}
- (void)doShare{
    
    //fromType 0:视频界面分享 1:三级分销分享
    [YBShareView showShareWithType:RKShareType_Invite parameter:@{} commplete:^(int codeEvent, NSString *nums) {
        
    }];
    
}
#pragma mark -
#pragma mark - navi

- (void)clickNaviLeftBtn {
    //重写父类，不要super
    if (_isGuide) {
        UIApplication *app =[UIApplication sharedApplication];
        AppDelegate *app2 = (AppDelegate *)app.delegate;
        YBNavigationController *nav = [[YBNavigationController alloc]initWithRootViewController:[[YBTabBarController alloc]initWithAlert:YES]];
        app2.window.rootViewController = nav;
        return ;
    }
    NSString *nowUrl = _WKWebView.URL.absoluteString;
    nowUrl = [nowUrl lowercaseString];
    if ([nowUrl containsString:@"appapi/auth/success"] ||
        [nowUrl containsString:@"appapi/agent/index"]) {
        [self dismissViewControllerAnimated:YES completion:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }else if ([_WKWebView canGoBack]) {
        //说明进入了二级或者三级等页面，此时执行 goback
        [_WKWebView goBack];
        if ([nowUrl containsString:@"appapi/agent/agent"]) {
            [self.WKWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_url]]];
        }
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    
}
- (void)clickNaviRightBtn {
    [self doShare];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
